package com.example.stlink.utils.activityUtil;

import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.stlink.activitys.MainActivity;
import com.example.stlink.R;
import com.example.stlink.model.constants.ModelFieldConstants;
import com.example.stlink.model.constants.SQLiteConstants;
import com.example.stlink.model.constants.UrlConstants;
import com.example.stlink.model.contract.UserInfoContract;
import com.example.stlink.model.domain.User;
import com.example.stlink.model.response.BaseResponse;
import com.example.stlink.utils.CommonUtils;
import com.example.stlink.utils.MySQLiteDAO;
import com.example.stlink.utils.httpUtils.PostBodyParamHttpUtils;
import com.google.android.material.textfield.TextInputLayout;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.internal.LinkedTreeMap;

public class LoginUtil {

    private static AppCompatActivity loginActivity;
    private static final LoginUtil LOGIN_UTIL = new LoginUtil();

    private static String userName;
    private static String pwdFirst;
    private static String pwd;
    private static TextInputLayout tlId;
    private static TextInputLayout tlPwd;
    private static Boolean isChecked;
    private static Integer roleId;

    private static Handler handler;
    private static Bundle bundle;

    private LoginUtil(){}


    /**
     * 用户登陆
     * @param appCompatActivity 上下文
     * @param btLogin 登录按钮
     * @param etAccount 账户输入
     * @param etPwd 密码输入
     * @param cbRememberPwd 是否保存密码
     */
    public static void userLogin(AppCompatActivity appCompatActivity,
                                 Button btLogin, EditText etAccount,
                                 EditText etPwd, CheckBox cbRememberPwd ){

        loginActivity = appCompatActivity;
        roleId = (Integer) appCompatActivity.getIntent().getExtras().get(ModelFieldConstants.ROLE_ID);

        //登录按钮
        btLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                pwdFirst = etPwd.getText().toString();
                userName = etAccount.getText().toString();
                isChecked = cbRememberPwd.isChecked();

                tlId = appCompatActivity.findViewById(R.id.ll_id);
                tlPwd = appCompatActivity.findViewById(R.id.ll_pwd);

                if( !TextUtils.isEmpty(userName) ){
                    tlId.setError("");
                    if( !TextUtils.isEmpty(pwdFirst)) {
                        tlPwd.setError("");
                        LOGIN_UTIL.loginRequest();
                        pwd = CommonUtils.encryptAndDencrypt(pwdFirst);
                        handler = new Handler(Looper.getMainLooper()){
                            @Override
                            public void handleMessage(@NonNull Message msg) {
                                super.handleMessage(msg);
                                if("当前登录用户不存在".equals(msg.obj.toString())){
                                    tlId.setError(msg.obj.toString());
                                }else if("密码错误".equals(msg.obj.toString())){
                                    tlPwd.setError(msg.obj.toString());
                                }else{
                                    Toast.makeText(
                                            appCompatActivity,
                                            "登录失败",
                                            Toast.LENGTH_SHORT
                                    ).show();
                                }
                            }
                        };
                    }else{
                        tlPwd.setError("密码不能为空");
                    }
                }else{
                    tlId.setError("用户名不能为空");
                }
            }
        });
    }


    /**
     * 登录请求
     */
    private void loginRequest(){
        new Thread(() -> {
            // 密码要进行MD5加密
            String url = UrlConstants.USER_LOGIN + "?password=" + CommonUtils.MD5(pwd) + "&username=" + userName;

            new PostBodyParamHttpUtils() {
                @Override
                public void nextMethod(BaseResponse<Object> baseResponse) {

                    //解析数据
                    Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
                    Object obj = baseResponse.getData();
                    LinkedTreeMap<String, String> userMap = null;
                    if(obj instanceof LinkedTreeMap){
                        userMap = (LinkedTreeMap<String, String>) obj;
                    }
                    //将LinkedTreeMap中字段映射到User类中
                    User user = new User();
                    String jsonString = gson.toJson(userMap);
                    user = gson.fromJson(jsonString, User.class);
                    System.out.println("user = " + user + "..................");
                    //身份校验
                    if(roleId.equals(user.getRoleId())){
                        Intent intent = new Intent(loginActivity, MainActivity.class);
                        bundle = loginActivity.getIntent().getExtras();
                        LOGIN_UTIL.saveUser(user);
                        intent.putExtras(bundle);
                        loginActivity.startActivity(intent);
                    }else{
                        Message message = new Message();
                        message.obj = "登录失败";
                        handler.sendMessage(message);
                    }
                }
                @Override
                public void failedMethod(BaseResponse<Object> baseResponse) {
                    Message message = new Message();
                    message.obj = baseResponse.getMsg();
                    handler .sendMessage(message);
                }
            }.postConnect(url, "");
        }).start();
    }

    /**
     * 将User插入到本地SQLite数据库中
     * @param user User实例
     */
    private void saveUser(@Nullable User user){
        // 密码保存到本地文件
        if(isChecked){
            CommonUtils.localSave(loginActivity, userName, pwdFirst, true);
        }
        if(user == null){
            System.out.println("user == null................");
            return;
        }

        saveUserIntoIntent(user);

        saveUserIntoSQLite(user);

    }

    /**
     * 用户信息保存到bundle中
     * @param user User实例
     */
    private void saveUserIntoIntent(User user){
        if(user.getId() != null){
            bundle.putLong(ModelFieldConstants.ID, user.getId());
        }
        if(user.getRoleId() != null){
            bundle.putInt(ModelFieldConstants.ROLE_ID, user.getRoleId());
        }
        if(user.getIdNumber() != null){
            bundle.putLong(ModelFieldConstants.ID_NUMBER, user.getIdNumber());
        }
        if(user.getRealName() != null){
            bundle.putString(ModelFieldConstants.REAL_NAME, user.getRealName());
        }
        if(user.getUserName() != null){
            bundle.putString(ModelFieldConstants.USER_NAME, user.getUserName());
        }
        if(user.getCollegeName() != null){
            bundle.putString(ModelFieldConstants.COLLEGE_NAME, user.getCollegeName());
        }
        if(user.getGender() != null){
            bundle.putBoolean(ModelFieldConstants.GENDER,user.getGender());
        }
        if(user.getAvatar() != null){
            bundle.putString(ModelFieldConstants.AVATAR, user.getAvatar());
        }
        if(user.getEmail() != null){
            bundle.putString(ModelFieldConstants.EMAIL, user.getEmail());
        }
        if(user.getPhone() != null){
            bundle.putString(ModelFieldConstants.PHONE, user.getPhone());
        }
        if(user.getInSchoolTime() != null){
            bundle.putLong(ModelFieldConstants.IN_SCHOOL_TIME, user.getInSchoolTime());
        }
        if(user.getCreateTime() != null){
            bundle.putLong(ModelFieldConstants.CREATE_TIME, user.getCreateTime());
        }
    }

    /**
     * 保存用户实例到SQLite
     * @param user 用户实例
     */
    private void saveUserIntoSQLite(User user){

        MySQLiteDAO mySQLiteDAO = MySQLiteDAO.newInstance();
        //在本地建立SQLite数据库
        mySQLiteDAO.createTable(
                loginActivity,
                SQLiteConstants.USER_INFO_DATABASE_NAME,
                null,
                SQLiteConstants.DATABASE_FIRST_VERSION,
                SQLiteConstants.USER_INFO_SQL_CREATE_ENTRIES,
                SQLiteConstants.USER_INFO_SQL_DELETE_ENTRIES
        );

        //插入数据
        ContentValues values = new ContentValues();
        values.put(UserInfoContract.UserEntry.COLUMN_NAME_APP_KEY, user.getAppKey());
        values.put(UserInfoContract.UserEntry.COLUMN_NAME_AVATAR, user.getAvatar());
        values.put(UserInfoContract.UserEntry.COLUMN_NAME_COLLEGE_NAME, user.getCollegeName());
        values.put(UserInfoContract.UserEntry.COLUMN_NAME_CREATE_TIME, user.getCreateTime());
        values.put(UserInfoContract.UserEntry.COLUMN_NAME_EMAIL, user.getEmail());
        //SQLite不支持存储boolean，用integer存
        values.put(UserInfoContract.UserEntry.COLUMN_NAME_GENDER, user.getGender() ? 0 : 1);
        values.put(UserInfoContract.UserEntry.COLUMN_NAME_ID, user.getId());
        values.put(UserInfoContract.UserEntry.COLUMN_NAME_ID_NUMBER, user.getIdNumber());
        values.put(UserInfoContract.UserEntry.COLUMN_NAME_IN_SCHOOL_TIME, user.getInSchoolTime());
        values.put(UserInfoContract.UserEntry.COLUMN_NAME_LAST_UPDATE_TIME, user.getLastUpdateTime());
        values.put(UserInfoContract.UserEntry.COLUMN_NAME_PHONE, user.getPhone());
        values.put(UserInfoContract.UserEntry.COLUMN_NAME_REAL_NAME, user.getRealName());
        values.put(UserInfoContract.UserEntry.COLUMN_NAME_ROLE_ID, user.getRoleId());
        values.put(UserInfoContract.UserEntry.COLUMN_NAME_USER_NAME, user.getUserName());

        boolean isSuccess = mySQLiteDAO.insertValue(
                UserInfoContract.UserEntry.TABLE_NAME,
                null,
                values
        );
        if(isSuccess){
            System.out.println("SQLite:insert success............");
        }else{
            System.out.println("SQLite:insert failed.............");
        }
    }
}
